package cloudContact;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import cloudContact.DAO.UserDAO;

public class SecurityManager {

	public static String getHash(String password)
			throws NoSuchAlgorithmException {
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		digest.reset();
		try {
			byte[] input = digest.digest(password.getBytes("UTF-8"));
			return byteToBase64(input);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * From a base 64 representation, returns the corresponding byte[]
	 * 
	 * @param data
	 *            String The base64 representation
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] base64ToByte(String data) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		return decoder.decodeBuffer(data);
	}

	/**
	 * From a byte[] returns a base 64 representation
	 * 
	 * @param data
	 *            byte[]
	 * @return String
	 * @throws IOException
	 */
	public static String byteToBase64(byte[] data) {
		BASE64Encoder endecoder = new BASE64Encoder();
		return endecoder.encode(data);
	}

	public static boolean CheckAuthorization(HttpServletRequest request)
			throws RollbackException, MyDAOException {
		HttpSession session = request.getSession(false);

		if (session == null) {
			return false;
		} else {
			if (session.getAttribute("authorized") == null
					|| session.getAttribute("authorized").equals(false)
					|| session.getAttribute("userId") == null
					|| session.getAttribute("userId").toString().equals("")) {
				return false;
			} else {
				String userName = session.getAttribute("userId").toString();
				UserDAO userDAO = UserDAO.getInstance();
				if (userDAO.lookup(userName) != null) {
					return true;
				} else {
					return false;
				}

			}
		}

	}
}
